package com.dongdongshop.service.impl;

import com.dongdongshop.data.Page;
import com.dongdongshop.mapper.TbSpecificationMapper;
import com.dongdongshop.mapper.TbSpecificationOptionMapper;
import com.dongdongshop.pojo.TbBrand;
import com.dongdongshop.pojo.TbSpecification;
import com.dongdongshop.pojo.TbSpecificationOption;
import com.dongdongshop.service.SpecService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@DubboService
public class SpecServiceImpl implements SpecService {

    @Autowired
    private TbSpecificationMapper tbSpecificationMapper;

    @Autowired
    private TbSpecificationOptionMapper tbSpecificationOptionMapper;

    @Override
    @Transactional
    public void add(TbSpecification tbSpecification, List<TbSpecificationOption> options) {
        tbSpecificationMapper.add(tbSpecification);

        for (int i = 0; i < options.size(); i++){
            options.get(i).setSpecId(tbSpecification.getId());
            tbSpecificationOptionMapper.insertSelective(options.get(i));
        }
    }

    @Override
    public Page<TbSpecification> list(Integer pageNum, Integer pageSize,TbSpecification tbSpecification) {
        PageHelper.startPage(pageNum,pageSize);
        List<TbSpecification> specification = tbSpecificationMapper.selectByName(tbSpecification);
        PageInfo<TbSpecification> pageInfo = new PageInfo(specification);
        Page<TbSpecification> page = new Page(pageInfo.getPageNum(),pageInfo.getPageSize(),pageInfo.getPages(),pageInfo.getList());
        return page;
    }

    @Override
    @Transactional
    public void deleteInfo(Integer[] ids) {
        tbSpecificationMapper.deleteById(ids);
        tbSpecificationOptionMapper.deleteBySpecId(ids);
    }

    @Override
    public TbSpecification toUpdate(Long id) {
        return tbSpecificationMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<TbSpecificationOption> toUpdateOption(Long id) {
        return tbSpecificationOptionMapper.selectBySid(id);
    }

    @Override
    @Transactional
    public void updateInfo(TbSpecification tbSpecification, List<TbSpecificationOption> options) {
        tbSpecificationMapper.updateByPrimaryKeySelective(tbSpecification);

        tbSpecificationOptionMapper.deleteBySid(tbSpecification.getId());
        for (int i = 0; i < options.size(); i++){
            options.get(i).setSpecId(tbSpecification.getId());
            tbSpecificationOptionMapper.insertSelective(options.get(i));
        }
    }

    @Override
    public List<TbSpecification> toShow() {
        return tbSpecificationMapper.selectByExample(null);
    }
}
